package com.woyao.core.model;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;

import java.io.IOException;
import java.util.ArrayList;

public class AreaArrayDeserializer extends JsonDeserializer<ArrayList<Area>> {

    public AreaArrayDeserializer(){

    }
    @Override
    public ArrayList<Area> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
            throws IOException, JsonProcessingException {

        JsonNode objectNode = jsonParser.readValueAsTree();

        if (null == objectNode                     // if no author node could be found
                || !objectNode.isArray()           // or author node is not an array
                || !objectNode.elements().hasNext())   // or author node doesn't contain any authors
            return null;
        ArrayNode node = (ArrayNode)objectNode;

        ArrayList<Area> list = new ArrayList<>();
        for(JsonNode each : node){
            Area area = new Area();
            area.setId(each.get("no").asInt(-1));
            area.setName(each.get("areaname").asText());
            area.setDescription(each.get("description").asText());
            area.setChilds(each.get("childs").asInt(0));
            list.add(area);
        }

        return list;
    }
}